<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="85px">
      <el-form-item label="领料单编号" prop="issueCode">
        <el-input v-model="queryParams.issueCode" placeholder="请输入领料单编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="领料单名称" prop="issueName">
        <el-input v-model="queryParams.issueName" placeholder="请输入领料单名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="仓库名称" prop="warehouseName">
        <el-input v-model="queryParams.warehouseName" placeholder="请输入仓库名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="领料日期" prop="issueDate">
        <el-date-picker clearable v-model="queryParams.issueDate" type="date" format="YYYY-MM-DD" placeholder="请选择领料日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['WmIssueHeader:WmIssueHeader:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['WmIssueHeader:WmIssueHeader:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['WmIssueHeader:WmIssueHeader:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['WmIssueHeader:WmIssueHeader:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="WmIssueHeaderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="领料单编号" align="center" prop="issueCode" />
      <el-table-column label="领料单名称" align="center" prop="issueName" />
      <el-table-column label="工作站名称" align="center" prop="workstationName" />
      <el-table-column label="生产工单编码" align="center" prop="workorderCode" />
      <el-table-column label="领料日期" align="center" prop="issueDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.issueDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
     
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['WmIssueHeader:WmIssueHeader:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['WmIssueHeader:WmIssueHeader:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageDto.current"
      v-model:limit="queryParams.pageDto.size" @pagination="getList" />

    <!-- 添加或修改生产领料单头对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="WmIssueHeaderRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="领料单编号" prop="issueCode">
              <el-input v-model="form.issueCode" placeholder="请输入领料单编号" disabled/>
              <el-switch v-model="autoGenerateCode" style="margin-left: 10px;" @change="handleCodeSwitchChange"
                active-text="自动生成"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="领料单名称" prop="issueName">
              <el-input v-model="form.issueName" placeholder="请输入领料单名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="需求时间" prop="issueDate">
              <el-date-picker clearable v-model="form.issueDate" type="date" format="YYYY-MM-DD"
                placeholder="请选择需求日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产工单" prop="workorderCode">
              <div style="display: flex;">
                <el-input v-model="form.workorderCode" placeholder="请选择生产工单" />
                <el-button icon="Search" @click="searchWorkorder" />
              </div>

            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工作站" prop="workstationCode">
              <div style="display: flex;">
                <el-input v-model="form.workstationCode" placeholder="请选择工作站" />
                <el-button icon="Search" @click="searchWorkstation" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作站名称" prop="workstationName">
              <el-input v-model="form.workstationName" placeholder="请输入工作站" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户编号" prop="clientCode">
              <el-input v-model="form.clientCode" placeholder="请输入客户编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="form.clientName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancel">关闭</el-button>
        </div>
      </template>
      <el-card style="max-width: 900px" v-show="flag">
          <template #header>
            <div class="card-header">
              <span><strong style="font: 90px;">物料信息</strong></span>
            </div>
          </template>
          <div>
                <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="Plus"
                  @click="handleAddLine"
                  v-hasPermi="['IssueLine:IssueLine:add']"
                >新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="Edit"
                  :disabled="singleLine"
                  @click="handleUpdateLine"
                  v-hasPermi="['IssueLine:IssueLine:edit']"
                >修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="Delete"
                  :disabled="multipleLine"
                  @click="handleDeleteLine"
                  v-hasPermi="['IssueLine:IssueLine:remove']"
                >删除</el-button>
              </el-col>
            </el-row>

            <el-table v-loading="loadingLine" :data="IssueLineList" @selection-change="handleSelectionChangeLine">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="产品物料编码" align="center" prop="itemCode" />
              <el-table-column label="产品物料名称" align="center" prop="itemName" />
              <el-table-column label="规格型号" align="center" prop="specification" />
              <el-table-column label="单位" align="center" prop="unitOfMeasure" />
              <el-table-column label="领料数量" align="center" prop="quantityIssued" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link type="primary" icon="Edit" @click="handleUpdateLine(scope.row)" v-hasPermi="['IssueLine:IssueLine:edit']">修改</el-button>
                  <el-button link type="primary" icon="Delete" @click="handleDeleteLine(scope.row)" v-hasPermi="['IssueLine:IssueLine:remove']">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <pagination
              v-show="totalLine>0"
              :total="totalLine"
              v-model:page="queryParamsLine.pageNum"
              v-model:limit="queryParamsLine.pageSize"
              @pagination="getListLine(nowId)"
            />

            <!-- 添加或修改生产领料单行对话框 -->
              <el-dialog v-model="open3"  :title="titletui" width="900px" @close="handleDialogClose3">
                <el-row :gutter="15">
                  <el-form ref="IssueLineRef" :model="formtui" :rules="rulestui" size="default" label-width="120px">
                    <el-col :span="24">
                      <el-row gutter="15">
                        <el-col :span="8">
                          <el-form-item label="物料编码" prop="itemCode">
                            <el-input v-model="formtui.itemCode" type="text" placeholder="请输入物料编码" clearable disabled
                              :style="{width: '100%'}"></el-input>
                            <el-icon @click="kaii1" style="border: 1px solid #DCDFE6;width: 30px;height: 30px;background-color: #F5F7FA;cursor: pointer;position: relative;left:155px;top:-31px"><Search /></el-icon>

                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="物料名称" prop="itemName">
                            <el-input v-model="formtui.itemName" type="text" placeholder="请输入物料名称" clearable disabled
                              :style="{width: '100%'}"></el-input>
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="单位" prop="unitOfMeasure">
                            <el-input v-model="formtui.unitOfMeasure" type="text" placeholder="请输入单位" clearable disabled
                              :style="{width: '100%'}"></el-input>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </el-col>
                    
                    <el-col :span="20">
                      <el-form-item label="规格型号" prop="specification">
                        <el-input v-model="formtui.specification" type="text" placeholder="请输入规格型号" clearable disabled
                          :style="{width: '100%'}"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-row gutter="15">
                        <el-col :span="11">
                          <el-form-item label="批次号" prop="batchCode" >
                            <el-input v-model="formtui.batchCode" type="text"  clearable disabled
                              :style="{width: '100%'}"></el-input>
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="领料数量" prop="quantityIssued">
                            <el-input v-model="formtui.quantityIssued" type="text" placeholder="请输入领料数量" clearable
                              :style="{width: '100%'}"></el-input>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </el-col>
                  </el-form>
                </el-row>
                <template #footer>
                  <el-button @click="cancelLine">取消</el-button>
                  <el-button type="primary" @click="submitFormLine">确定</el-button>
                </template>
              </el-dialog>
              <!-- 物料选择 -->
              <el-dialog v-model="open4" width="1200px"   @close="handleDialogClose1">
                  <el-container>
                    <el-aside width="200px" style="background-color: white;">
                    <el-table
                      style="border: none;"
                      v-if="refreshTable"
                      :data="type1List"
                      row-key="itemTypeId"
                      :default-expand-all="isExpandAll"
                      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                      @row-click="handleCategoryClick" > <!-- 新增：点击分类行触发查询 -->
                      <el-table-column  align="center" prop="itemTypeName" />
                    </el-table>
                      </el-aside>
                      <el-main>
                    <el-form :model="queryParams2" ref="queryRef" :inline="true" v-show="showSearch2" label-width="68px">
                      <el-form-item label="物料编码" prop="itemCode">
                        <el-input
                          v-model="queryParams2.itemCode"
                          placeholder="请输入产品物料编码"
                          clearable
                          @keyup.enter="handleQuery2"
                        />
                      </el-form-item>
                      <el-form-item label="物料名称" prop="itemName">
                        <el-input
                          v-model="queryParams2.itemName"
                          placeholder="请输入产品物料名称"
                          clearable
                          @keyup.enter="handleQuery2"
                        />
                      </el-form-item>
                      <el-form-item label="批次号" prop="batchCode">
                        <el-input
                          v-model="queryParams2.batchCode"
                          placeholder="请输入批次号"
                          clearable
                          
                          @keyup.enter="handleQuery2"
                        />
                      </el-form-item>
                      <el-form-item label="仓库" prop="warehouseName">
                        <el-input
                          v-model="queryParams2.warehouseName"
                          placeholder="请输入仓库"
                          clearable
                          @keyup.enter="handleQuery2"
                        />
                      </el-form-item>
                      <el-form-item label="库区" prop="locationName">
                        <el-input
                          v-model="queryParams2.locationName"
                          placeholder="请输入库区"
                          clearable
                          @keyup.enter="handleQuery2"
                        />
                      </el-form-item>
                      <el-form-item label="库位" prop="areaName">
                        <el-input
                          v-model="queryParams2.areaName"
                          placeholder="请输入库位"
                          clearable
                          @keyup.enter="handleQuery2"
                        />
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery2">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery2">重置</el-button>
                      </el-form-item>
                    </el-form>

                  <el-table v-loading="loading2" ref="userTableRef" :data="userList1" 
                  @row-click="handleTableRowClick" :highlight-current-row="true" @select="handleRadioChange2">
                    <el-table-column type="radio" width="50" />
                    <el-table-column label="物料编码" align="center" prop="itemCode" />
                    <el-table-column label="物料名称" align="center" prop="itemName" />
                    <el-table-column label="规格型号" align="center" prop="specification" />
                    <el-table-column label="在库数量" align="center" prop="quantityOnhand" />
                    <el-table-column label="单位" align="center" prop="unitOfMeasure" />
                    <el-table-column label="批次号" align="center" prop="batchCode" />
                    <el-table-column label="仓库" align="center" prop="warehouseName" />
                    <el-table-column label="库区" align="center" prop="locationName" />
                    <el-table-column label="库位" align="center" prop="areaName" />
                    <el-table-column label="入库时间" align="center" prop="recptDate" width="180">
                      <template #default="scope">
                        <span>{{ parseTime(scope.row.recptDate, '{y}-{m}-{d}') }}</span>
                      </template>
                    </el-table-column>
                    
                  </el-table>
                  
                  <pagination
                    v-show="total2>0"
                    :total="total2"
                    v-model:page="queryParams2.pageNum"
                    v-model:limit="queryParams2.pageSize"
                    @pagination="getList2"
                  />
                </el-main>
                </el-container>
                <el-button style="margin-left: 950px;" type="primary" @click="confirmSelectedItem2">确 认</el-button>
                <el-button @click="cancel1">关 闭</el-button>
              </el-dialog>
          </div>
      </el-card>

      <!-- 生产工单的弹窗 -->
      <el-dialog v-model="workOrderVisible" width="1000" title="生产工单选择" center append-to-body>
        <div class="app-container">
          <el-form :model="queryParamsWorkOrder" ref="queryRefWorkOrder" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="工单编码" prop="workorderCode">
              <el-input v-model="queryParamsWorkOrder.workorderCode" placeholder="请输入工单编码" clearable
                @keyup.enter="handleQueryWorkOrder" />
            </el-form-item>
            <el-form-item label="工单名称" prop="workorderName">
              <el-input v-model="queryParamsWorkOrder.workorderName" placeholder="请输入工单名称" clearable
                @keyup.enter="handleQueryWorkOrder" />
            </el-form-item>
            <el-form-item label="产品编号" prop="productCode">
              <el-input v-model="queryParamsWorkOrder.productCode" placeholder="请输入产品编号" clearable
                @keyup.enter="handleQueryWorkOrder" />
            </el-form-item>
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="queryParamsWorkOrder.productName" placeholder="请输入产品名称" clearable
                @keyup.enter="handleQueryWorkOrder" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQueryWorkOrder">搜索</el-button>
              <el-button icon="Refresh" @click="resetQueryWorkOrder">重置</el-button>
            </el-form-item>
          </el-form>

<!-- 工单弹窗 -->
          <el-table v-loading="loading" :data="workorderList" @row-click="handleWorkorderRowClick"
            :highlight-current-row="true" ref="workorderTableRef" @select="handleWorkorderSelect">
            <el-table-column type="radio" width="50" />
            <el-table-column label="工单编码" align="center" prop="workorderCode" />
            <el-table-column label="工单名称" align="center" prop="workorderName" />
            <el-table-column label="工单类型" align="center" prop="orderType">
              <template #default="scope">
                <dict-tag :options="sys_workorder_type" :value="scope.row.orderType" />
              </template>
            </el-table-column>
            <el-table-column label="工单来源" align="center" prop="orderSource" />
            <el-table-column label="产品编号" align="center" prop="productCode" />
            <el-table-column label="产品名称" align="center" prop="productName" />
            <el-table-column label="规格型号" align="center" prop="productSpc" />
            <el-table-column label="单位" align="center" prop="unitOfMeasure" />
            <el-table-column label="工单数量" align="center" prop="quantity" width="80" />
            <el-table-column label="已生产数量" align="center" prop="quantityProduced" width="120" />
            <el-table-column label="调整数量" align="center" prop="quantityChanged" width="80" />
            <el-table-column label="需求日期" align="center" prop="requestDate" width="120">
              <template #default="scope">
                <span>{{ parseTime(scope.row.requestDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="单据状态" align="center" prop="status" width="80" />
          </el-table>

          <pagination v-show="totalWorkOrder > 0" :total="totalWorkOrder" v-model:page="queryParamsWorkOrder.pageNum"
            v-model:limit="queryParamsWorkOrder.pageSize" @pagination="getListWorkOrder" />
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="workOrderVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmWorkorder">
              确定工单
            </el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 工作站的弹窗 -->
      <el-dialog v-model="workStationVisible" width="1000" title="工作站选择" center append-to-body>
        <div class="app-container">
          <el-form :model="queryParamsWorkStation" ref="queryRefWorkStation" :inline="true" v-show="showSearch"
            label-width="100px">
            <el-form-item label="工作站编码" prop="workstationCode">
              <el-input v-model="queryParamsWorkStation.workstationCode" placeholder="请输入工作站编码" clearable
                @keyup.enter="handleQueryWorkStation" />
            </el-form-item>
            <el-form-item label="工作站名称" prop="workstationName">
              <el-input v-model="queryParamsWorkStation.workstationName" placeholder="请输入工作站名称" clearable
                @keyup.enter="handleQueryWorkStation" />
            </el-form-item>
            <el-form-item label="所在车间名称" prop="workshopName">
              <el-select v-model="queryParamsWorkStation.workshopCode" placeholder="请选择车间" clearable
                style="width: 240px">
                <el-option v-for="item in workshopOptions" :key="item.workshopId" :label="item.workshopName"
                  :value="item.workshopCode" />
              </el-select>
            </el-form-item>
            <el-form-item label="所属工序" prop="processName">
              <el-select v-model="queryParamsWorkStation.processCode" placeholder="请选择工序" clearable
                style="width: 240px">
                <el-option v-for="(item, index) in processCodeOptions" :key="item.processId" :label="item.processName"
                  :value="item.processCode" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQueryWorkStation">搜索</el-button>
              <el-button icon="Refresh" @click="resetQueryWorkStation">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table v-loading="loading" :data="workstationList" @row-click="handleWorkstationRowClick"  @select="handleStationelect"
            :highlight-current-row="true" ref="workstationTableRef">
            <el-table-column type="radio" width="50" />
            <el-table-column label="工作站ID" align="center" prop="workstationId" />
            <el-table-column label="工作站编码" align="center" prop="workstationCode" />
            <el-table-column label="工作站名称" align="center" prop="workstationName" />
            <el-table-column label="工作站地点" align="center" prop="workstationAddress" />
            <el-table-column label="所在车间名称" align="center" prop="workshopName" />
            <el-table-column label="工序名称" align="center" prop="processName" />
            <el-table-column label="是否启用" align="center" prop="enableFlag" />
            <el-table-column label="备注" align="center" prop="remark" />
          </el-table>
          <pagination v-show="totalWorkStation > 0" :total="totalWorkStation"
            v-model:page="queryParamsWorkStation.pageNum" v-model:limit="queryParamsWorkStation.pageSize"
            @pagination="getListWorkstation" />
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="workStationVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmWorkStation">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup name="WmIssueHeader">
import { listWmIssueHeader, getWmIssueHeader, delWmIssueHeader, addWmIssueHeader, updateWmIssueHeader } from "@/api/WmIssueHeader/WmIssueHeader"
import { listWorkorder } from "@/api/schedule/schedule"
import { listWorkstation, listWorkshop, listProcess } from "@/api/workstation/workstation"
const workorderList = ref([])//接收工单列表
const totalWorkOrder = ref(0)//工单列表总数

const workstationList = ref([])//接收工作站列表
const totalWorkStation = ref(0)

const workshopOptions = ref([])//车间下拉列表
const processCodeOptions = ref([])//工序下拉列表

//-------------------------------工单弹窗开始----------------------------------

// 添加当前选中的工单引用
const currentWorkorder = ref(null)
const workorderTableRef = ref(null)

// 工单表格行点击事件
function handleWorkorderRowClick(row) {
  //console.log('选中的工单：', row);
  currentWorkorder.value = row;
  if (workorderTableRef.value) {
    workorderTableRef.value.setCurrentRow(row);
  }
}
// 选择工单按钮
function searchWorkorder() {
  // 打开弹窗前重置选中状态
  currentWorkorder.value = null;
  if (workorderTableRef.value) {
    workorderTableRef.value.setCurrentRow(null);
    workorderTableRef.value.clearSelection(); // 清空 radio 选中
  }
  // 获取工单列表并显示弹窗
  getListWorkOrder();
  workOrderVisible.value = true;
}
// 确认选择工单
function confirmWorkorder() {
  if (!currentWorkorder.value) {
    proxy.$modal.msgWarning("请先选择一条工单记录")
    return
  }

  // 将选中的工单编码赋值给主表单
  form.value.workorderId = currentWorkorder.value.workorderId
  form.value.workorderCode = currentWorkorder.value.workorderCode
  // 可以根据需要同时赋值其他字段，如工单名称等
  form.value.workorderName = currentWorkorder.value.workorderName

  // 关闭工单选择弹窗
  workOrderVisible.value = false
  // proxy.$modal.msgSuccess("工单选择成功")
}
//---------------------------------工单弹窗结束--------------------






//---------------------------------工作站弹窗开始--------------------
// 选择工作站按钮
function searchWorkstation() {
  getListWorkstation()
  getWorkshopList()//查询车间下拉列表
  getProcessList()//查询工序下拉列表
  workStationVisible.value = true

}

//查询车间列表
function getWorkshopList() {
  loading.value = true
  listWorkshop().then(response => {
    workshopOptions.value = response.data
    loading.value = false

  })
}
//查询工序列表
function getProcessList() {
  loading.value = true
  listProcess().then(response => {
    processCodeOptions.value = response.data
    loading.value = false
  })
}

// 添加当前选中的工作站引用
const currentWorkstation = ref(null)
const workstationTableRef = ref(null)

// 工作站表格行点击事件
function handleWorkstationRowClick(row) {
 // console.log(row);

  currentWorkstation.value = row
  // 设置当前行为选中状态
  workstationTableRef.value.setCurrentRow(row)
}

// 确认选择工作站
function confirmWorkStation() {
  //console.log(currentWorkstation.value);

  if (!currentWorkstation.value) {
    proxy.$modal.msgWarning("请先选择一个工作站记录")
    return
  }
  // 将选中的工作站编码赋值给主表单
  form.value.workstationId= currentWorkstation.value.workstationId
  form.value.workstationCode = currentWorkstation.value.workstationCode
  // 可以根据需要同时赋值其他字段，如工作站名称等
  form.value.workstationName = currentWorkstation.value.workstationName

  // 关闭工单选择弹窗
  workStationVisible.value = false
}

//---------------------------------工作站弹窗结束--------------------


// 新增：自动生成编码开关状态
const autoGenerateCode = ref(false)
/** 生成仓库编码（规则：WS-YYYYMMDDHHmmss，如WS-20240520143025） */
function generateWorkshopCode() {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')
  const code = `IH${year}${month}${day}${hour}${minute}${second}`
  form.value.issueCode = code
}

/** 自动生成开关变化事件 */
function handleCodeSwitchChange() {
  if (autoGenerateCode.value) {
    generateWorkshopCode()
  } else {
    form.value.issueCode = null  // 关闭时清空手动输入
  }
}



const { proxy } = getCurrentInstance()
const { sys_workorder_type } = proxy.useDict('sys_workorder_type')
const WmIssueHeaderList = ref([])
const open = ref(false)//最外层弹窗控制
const workOrderVisible = ref(false)//工单弹窗控制
const workStationVisible = ref(false)//工站弹窗控制
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageDto: {
      current: 1,
      size: 10,
    },
    issueCode: null,
    issueName: null,
    warehouseName: null,
    issueDate: null,
  },
  rules: {
    issueCode: [
      { required: true, message: "领料单编号不能为空", trigger: "blur" }
    ],
    issueName: [
      { required: true, message: "领料单名称不能为空", trigger: "blur" }
    ],
  },
  // 工单查询条件
  queryParamsWorkOrder: {
    current: 1,
    size: 10,
    productName: null,
    productCode: null,
    workorderName: null,
    workorderCode: null
  },
  // 工作站查询条件
  queryParamsWorkStation: {
    pageNum: 1,
    pageSize: 10,
    workstationName: null,
    workstationCode: null,
    processCode: null,
    workshopCode: null,
  },
})

const { queryParams, queryParamsWorkOrder, queryParamsWorkStation, form, rules } = toRefs(data)

/** 查询生产领料单头列表 */
function getList() {
  loading.value = true
  listWmIssueHeader(queryParams.value).then(response => {
    WmIssueHeaderList.value = response.data.records
    total.value = response.data.pageDto.total
    loading.value = false
  })
}

/**查询工单列表 */
function getListWorkOrder() {
  listWorkorder(queryParamsWorkOrder.value).then(response => {
    workorderList.value = response.rows
    totalWorkOrder.value = response.total
  })
}

/**查询工作站列表*/
function getListWorkstation() {
  //console.log("queryParamsWorkStation.value", queryParamsWorkStation.value)
  listWorkstation(queryParamsWorkStation.value).then(response => {
    //console.log("工作站列表", response);
    workstationList.value = response.rows
    totalWorkStation.value = response.total
  })
}

// 取消按钮
function cancel() {
  autoGenerateCode.value=false
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    issueId: null,
    issueCode: null,
    issueName: null,
    workstationId: null,
    workstationCode: null,
    workstationName: null,
    workorderId: null,
    workorderCode: null,
    taskId: null,
    taskCode: null,
    clientId: null,
    clientCode: null,
    clientName: null,
    clientNick: null,
    warehouseId: null,
    warehouseCode: null,
    warehouseName: null,
    locationId: null,
    locationCode: null,
    locationName: null,
    areaId: null,
    areaCode: null,
    areaName: null,
    issueDate: null,
    status: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("WmIssueHeaderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
 // console.log("queryParams.value", queryParams.value)
  queryParams.value.pageDto.current = 1
  getList()
}
/**搜索工单列表 */
function handleQueryWorkOrder() {
  queryParamsWorkOrder.value.current = 1
  getListWorkOrder()
}
/**搜索工作站列表 */
function handleQueryWorkStation() {
  queryParamsWorkStation.value.pageNum = 1
  getListWorkstation()
}




/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}
/**重置工单列表搜索条件 */
function resetQueryWorkOrder() {
  proxy.resetForm("queryRefWorkOrder")
  handleQueryWorkOrder()
}
/**重置工作站列表搜索条件 */
function resetQueryWorkStation() {
  proxy.resetForm("queryRefWorkStation")
  handleQueryWorkStation()
}



// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.issueId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  autoGenerateCode.value=false
  reset()
  open.value = true
  flag.value=false
  title.value = "添加生产领料"
}

/** 头修改按钮操作 */
const nowId=ref()
function handleUpdate(row) {
  // console.log(row);
  
   nowId.value=row.issueId
   getListLine(row.issueId)
  flag.value=true
  reset()
  const _issueId = row.issueId || ids.value
  getWmIssueHeader(_issueId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改生产领料单头"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["WmIssueHeaderRef"].validate(valid => {
    if (valid) {
      //console.log("form.value", form.value);

      if (form.value.issueId != null) {
        updateWmIssueHeader(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addWmIssueHeader(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}
import {deleteLine} from '@/api/WmIssueHeader/WmIssueHeader'
/** 删除按钮操作 */ 
async function handleDelete(row) {
  const _issueIds = row.issueId || ids.value;
  if (!_issueIds) {
    proxy.$modal.msgWarning("请选择要删除的领料单");
    return;
  }

  // 步骤1：先删除行表数据
  try {
    await deleteLine([_issueIds]); 
  } catch (error) {
    proxy.$modal.msgError("行表删除失败：" + error.message);
    return; // 行表删除失败，终止头表删除
  }

  // 步骤2：再删除头表数据
  proxy.$modal.confirm('是否确认删除生产领料单头编号为"' + _issueIds + '"的数据项？').then(async () => {
    await delWmIssueHeader(_issueIds);
    getList(); // 刷新列表
    proxy.$modal.msgSuccess("数据删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('WmIssueHeader/WmIssueHeader/export', {
    ...queryParams.value
  }, `WmIssueHeader_${new Date().getTime()}.xlsx`)
}

getList()

//------------------------------生产领料单行表数据渲染开始
const flag=ref(false)
import { listIssueLine, getIssueLine, delIssueLine, addIssueLine, updateIssueLine } from "@/api/IssueLine/IssueLine"

const IssueLineList = ref([])
const loadingLine = ref(true)
const idsLine = ref([])
const singleLine = ref(true)
const multipleLine = ref(true)
const totalLine = ref(0)
const titleLine = ref("")

const dataLine = reactive({
  formtui: {},
  queryParamsLine: {
    pageNum: 1,
    pageSize: 10,
  },
  rulestui: {
      quantityIssued: [
        { 
          required: true, 
          message: '请输入领料数量', 
          trigger: 'blur' 
        },
        {
          validator: (rule, value, callback) => {
            // 先判断输入是否为有效数字
            if (isNaN(Number(value))) {
              callback(new Error('请输入有效的数字'));
            } 
            // 检查是否小于 quality.value
            else if (Number(value) > Number(quality.value)) {
              callback(new Error(`领料数量不得高于${quality.value}`));
            } 
            // 验证通过
            else {
              callback();
            }
          },
          trigger: 'blur' // 失去焦点时触发验证，也可添加 'change' 实时验证
        }
    ],
    itemCode: [
      { required: true, message: "物料编码不能为空", trigger: "blur" }
    ]
  }
})

const { queryParamsLine, formtui, rulestui } = toRefs(dataLine)
import {listLine1} from '@/api/WmIssueHeader/WmIssueHeader'
/** 查询生产领料单行列表 */
async function getListLine(nowId) {
  if (!nowId) {
    proxy.$modal.msgError("领料单ID不能为空，无法加载行数据");
    loadingLine.value = false
    return; // 终止函数，不向后端发请求
  }
  loadingLine.value = true;
  try {
    const response = await listLine1(nowId); 
   IssueLineList.value = response.data
    totalLine.value = response.total
  } catch (error) {
    console.error("加载行列表失败：", error);
    proxy.$modal.msgError("加载行数据失败，请重试");
  } finally {
    // 无论成功/失败，都关闭加载状态
    loadingLine.value = false
  }
}



// 表单重置
function resetLine() {
  formtui.value = {
    lineId: null,
    issueId: null,
    materialStockId: null,
    itemId: null,
    itemCode: null,
    itemName: null,
    specification: null,
    unitOfMeasure: null,
    quantityIssued: null,
    batchCode: null,
    warehouseId: null,
    warehouseCode: null,
    warehouseName: null,
    locationId: null,
    locationCode: null,
    locationName: null,
    areaId: null,
    areaCode: null,
    areaName: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("IssueLineRef")
}

// 多选框选中数据
function handleSelectionChangeLine(selection) {
  idsLine.value = selection.map(item => item.lineId)
  singleLine.value = selection.length != 1
  multipleLine.value = !selection.length
}

/** 新增按钮操作 */
function handleAddLine() {
  resetLine()
  open3.value = true
  titleLine.value = "添加生产领料单行"
}

const oldCount=ref()
/** 行修改按钮操作 */
function handleUpdateLine(row) {
  
  oldCount.value=row.quantityIssued  
  resetLine()
  const _lineId = row.lineId || idsLine.value
  getIssueLine(_lineId).then(response => {
    formtui.value = response.data
    open3.value = true
    titleLine.value = "修改生产领料单行"
  })
}

/** 提交按钮 */
import {updataliang} from '@/api/line/line'
const newCount=ref()
const IssueLineRef=ref()

function submitFormLine() {
   formtui.value.issueId =nowId.value
  //根据id修改仓库数量
  IssueLineRef.value.validate((valid) => {
    if (valid) {
      if (formtui.value.lineId != null) {
         newCount.value=oldCount.value-formtui.value.quantityIssued
        updataliang(formtui.value.materialStockId,newCount.value)
        updateIssueLine(formtui.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open3.value = false
          getListLine(nowId.value)
        })
      } else {
        updataliang(formtui.value.materialStockId,-formtui.value.quantityIssued)
        addIssueLine(formtui.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open3.value = false
          getListLine(nowId.value)
        })
      }
    }
  })
}
// 取消按钮
function cancelLine() {
  open3.value = false
  resetLine()
}
/** 删除按钮操作 */
function handleDeleteLine(row) {
  console.log();
  const _lineIds = row.lineId || idsLine.value
  proxy.$modal.confirm('是否确认删除生产领料单行编号为"' + row.itemCode + '"的数据项？').then(function() {
    return delIssueLine(_lineIds)
  }).then(() => {
     updataliang(row.materialStockId,row.quantityIssued)//删除库存量增加
     getListLine(nowId.value)
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}


//-------------------------------------生产领料单行表数据渲染结束
//-------------------------------------物料展示开始
// 物料
const open3 = ref(false)
const open4=ref(false)
//查看物料
 function kaii1() {
    open4.value=true
}
import { listStock} from "@/api/stock/stock"


const loading2 = ref(true)
const showSearch2 = ref(true)
const total2 = ref(0)

const data2 = reactive({
  formItem: {},
  queryParams2: {
    pageNum: 1,
    pageSize: 10,
    itemCode: null,
    itemName: null,
    itemTypeName: null,
     itemTypeId: 1,  // 新增：用于存储选中的物料分类ID
  },
})

const { queryParams2} = toRefs(data2)
const userList1 = ref([]);
/** 查询物料产品管理列表 */
function getList2() {
  loading2.value = true
  listStock(queryParams2.value).then(response => {
    userList1.value = response.rows
    total2.value = response.total
    loading2.value = false
  })
}



/** 搜索按钮操作 */
function handleQuery2() {
  queryParams2.value.pageNum = 1
  getList2()
}

/** 重置按钮操作 */
function resetQuery2() {
  proxy.resetForm("queryRef")
    // 清除分类ID查询条件
  queryParams2.value.itemTypeId = 1
  handleQuery2()
}
getList2()
const type1List = ref([])
const isExpandAll = ref(true)
const refreshTable = ref(true)
const data4 = reactive({
  queryParams4: {
  },
})

const { queryParams4 } = toRefs(data4)

/** 查询物料分类列表 */
function getList6() {
  loading2.value = true
  listType1(queryParams4.value).then(response => {
    type1List.value = proxy.handleTree(response.data, "itemTypeId", "parentTypeId")
    loading2.value = false
  })
}
getList6()


//下拉表
import { listType1} from "@/api/type1/type1"
//---------------------------------------------物料展示开始结束
//----------------------------------------------------物料选择开始
// 处理物料分类点击事件
function handleCategoryClick(row) {
  // 设置选中的分类ID到查询参数
  queryParams2.value.itemTypeId = row.itemTypeId
  // 重置页码为1
  queryParams2.value.pageNum = 1
  // 执行查询
  getList2()
}
const selectedUser = ref(null);
const userTableRef = ref(null); // 用于获取el-table实例
// 处理单选框变化事件
function handleRadioChange2(selection) {
  // 单选情况下，selection数组只会有0或1个元素
  selectedUser.value = selection.length > 0 ? selection[0] : null;
}

function handleTableRowClick(row) {
  console.log("点击的行对象：", row);
  selectedUser.value = row
  userTableRef.value.setCurrentRow(row)
}
const quality=ref()
// 确认选择按钮
function confirmSelectedItem2() {
  if (!selectedUser.value) {
    proxy.$modal.msgWarning("请选择一个物料");
    return;
  }
  // console.log("物料");
  // console.log(selectedUser.value);
  // 将选中的物料信息回填到表单
  quality.value=selectedUser.value.quantityOnhand
  formtui.value.materialStockId = selectedUser.value.materialStockId;
  formtui.value.itemId = selectedUser.value.itemId;
  formtui.value.itemCode = selectedUser.value.itemCode;
  formtui.value.batchCode = selectedUser.value.batchCode;
  formtui.value.itemName = selectedUser.value.itemName;
  formtui.value.specification = selectedUser.value.specification;
  formtui.value.unitOfMeasure = selectedUser.value.unitOfMeasure;
  console.log(quality.value);
  
  // 关闭物料选择框
  open4.value = false;
  selectedUser.value = null;
  if (userTableRef.value) {
    userTableRef.value.clearSelection();
  }
}

// 对话框关闭时的处理方法
const handleDialogClose1 = () => {
  open4.value = false;
  // 重置选中状态（关键：避免下次打开弹窗时保留上次选择）
  selectedUser.value = null;
  if (userTableRef.value) {
    userTableRef.value.clearSelection();
    userTableRef.value.setCurrentRow(null); // 取消行高亮
  }
};
const handleDialogClose3 = () => {
  open3.value = false; // 只关闭内层弹窗，不影响主表单
};
//--------------------------------------------物料选择结束

</script>
